<template>
  <el-form label-position="top" :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="旧密码" prop="oldPwd">
      <el-input type="password" v-model="ruleForm.oldPwd" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newPwd">
      <el-input type="password" v-model="ruleForm.newPwd" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">修改密码</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import { updatePwd } from 'network/admin'

  export default {
    name: 'UpdatePwd',
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入旧密码'))
        } else {
          if (this.ruleForm.newPwd !== '') {
            this.$refs.ruleForm.validateField('newPwd')
          }
          callback()
        }
      }
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'))
        } else if (value === this.ruleForm.oldPwd) {
          callback(new Error('新密码不能与旧密码一致!'))
        } else {
          callback()
        }
      }
      return {
        ruleForm: {
          oldPwd: '',
          newPwd: ''
        },
        rules: {
          oldPwd: [
            { min: 6, max: 10, message: '长度在6-10个字符之间', trigger: 'blur' },
            { validator: validatePass, trigger: 'blur' }
          ],
          newPwd: [
            { min: 6, max: 10, message: '长度在6-10个字符之间', trigger: 'blur' },
            { validator: validatePass2, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            updatePwd(this.ruleForm.oldPwd, this.ruleForm.newPwd).then(res => {
              if (res.status === 1) return this.$message({
                type: 'error',
                message: res.message
              })
              this.$message({
                type: 'success',
                message: '重置密码成功！'
              })
              this.resetForm(formName)
            })
          } else {
            this.$message({
              type: 'error',
              message: '请输入完整且正确的信息！'
            })
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
        this.$refs[formName].clearValidate()
      }
    },
    beforeDestroy() {
      this.resetForm('ruleForm')
    }
  }
</script>

<style scoped>
  .el-form {
    width: 30%;
    background-color: #fff;
    padding: 20px;
    margin: 50px auto;
    border-radius: 5px;
    box-shadow: 1px 1px 5px #ddd;
  }

  .el-form-item:nth-child(3) {
    margin-top: 40px;
    text-align: center;
  }
</style>